package com.bbs.system.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bbs.model.controllers.UserManageController;

public class IllegalLinkedFilter implements Filter {

	// 防止BUG全部重写Filter类里的方法
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void destroy() {

	}

	/**
	 * 过滤器主要功能实现
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		// System.out.println("防盗链过滤器运行了");
		// 1. 请求和响应对象进行类型转换
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		// 2. 获取session，提取用户登录的信息
		HttpSession session = req.getSession();

		Object user = session.getAttribute(UserManageController.CURRENT_USER);
		// 3. 判断是否登录
		if (null != user) {
			// 用户已经登录了
			// 放行
			chain.doFilter(request, response);
		} else {
			// 用户没有登录
			// 判断所访问的资源

			String url = req.getRequestURI();

			// 判断资源
			if (url.endsWith("/checkname") || url.endsWith("/reg") || url.endsWith("/login")
					|| url.endsWith("/adminlogin") || url.endsWith("/adminlogin.html") || url.endsWith("/login.html")
					|| url.endsWith("/register.html") || url.endsWith(".js") || url.endsWith(".css")
					|| url.endsWith(".woff2") || url.endsWith(".woff") || url.endsWith(".ttf") || url.endsWith(".png")
					|| url.endsWith(".gif") || url.endsWith(".eot") || url.endsWith(".svg")
					|| url.endsWith("/fgtpassword1.html") || url.endsWith("/fgtpassword2.html")
					|| url.endsWith("/fgtpassword3.html") || url.endsWith("/main.html") || url.endsWith("/getcuruser")
					|| url.endsWith(".jpg") || url.endsWith("/logout") || url.endsWith("/getsecq")
					|| url.endsWith("/getsecquser") || url.endsWith("/checkseca") || url.endsWith("/modpassword")
					|| url.endsWith("/checkuserstatus")) {
				// 不需要身份验证，放行
				chain.doFilter(request, response);
			} else {
				// 盗链，跳转到登录页面
				System.out.println("盗链访问");
				System.out.println(url);
				resp.sendRedirect("/bbs/login.html");

			}
		}

	}

}
